/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.helpdesk.controllers.util;

import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.mail.*;

/**
 *
 * @author JK
 */
public class Mailer implements Runnable {

    private final String from;
    private final String to;
    private final String subject;
    private final String message;
    private String hostName;
    private int smtpPort;
    private String username;
    private String password;
    private boolean html;

    public Mailer(String from, String to, String subject, String message) {
        this.from = from;
        this.to = to;
        this.subject = subject;
        this.message = message;

        hostName = "smtp.gmail.com";
        smtpPort = 587;
        username = "hehekakaka@gmail.com";
        password = "123@456@";

    }

    public String getHostName() {
        return hostName;
    }

    public void setHostName(String hostName) {
        this.hostName = hostName;
    }

    public int getSmtpPort() {
        return smtpPort;
    }

    public void setSmtpPort(int smtpPort) {
        this.smtpPort = smtpPort;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public boolean isHtml() {
        return html;
    }

    public void setHtml(boolean html) {
        this.html = html;
    }

    private void sendSimple() throws EmailException {
        SimpleEmail email = new SimpleEmail();
        email.setHostName(hostName);
        email.setSmtpPort(smtpPort);
        email.setSSL(true);
        email.setAuthentication(username, password);
        email.addTo(to);
        email.setFrom(from);
        email.setSubject(subject);
        email.setMsg(message);
        email.send();
    }

    private void sendHTML() throws EmailException {
        HtmlEmail email = new HtmlEmail();
        email.setHostName(hostName);
        email.setSmtpPort(smtpPort);
        email.setSSL(true);
        email.setAuthentication(username, password);
        email.addTo(to);
        email.setFrom(from);
        email.setSubject(subject);
        email.setHtmlMsg(message);
        email.send();
    }

    @Override
    public void run() {
        try {
            if (html) {
                sendHTML();
            } else {
                sendSimple();
            }
        } catch (EmailException ex) {
            Logger.getLogger(Mailer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
